<template>
  <view class="available-tasks-container">
    <!-- 顶部导航 -->
    <cu-custom bgColor="bg-gradual-green" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content">可领取任务</block>
      <block slot="right">
        <text class="cuIcon-refresh text-white" @tap="refreshData"></text>
      </block>
    </cu-custom>

    <!-- 筛选栏 -->
    <view class="cu-bar bg-white solid-bottom">
      <view class="action">
        <text class="cuIcon-search text-gray"></text>
        <input 
          v-model="searchKeyword" 
          placeholder="搜索任务编号、工种" 
          class="margin-left-sm"
          @input="onSearchInput"
        />
      </view>
      <view class="action">
        <text class="cuIcon-filter text-blue" @tap="showFilterModal = true"></text>
      </view>
    </view>

    <!-- 统计信息 -->
    <view class="cu-card case margin-top-sm">
      <view class="cu-item shadow">
        <view class="cu-list grid col-3 no-border">
          <view class="cu-item">
            <text class="cuIcon-form text-blue"></text>
            <text class="text-sm">可领取</text>
            <text class="text-bold">{{stats.available}}</text>
          </view>
          <view class="cu-item">
            <text class="cuIcon-time text-orange"></text>
            <text class="text-sm">紧急任务</text>
            <text class="text-bold">{{stats.urgent}}</text>
          </view>
          <view class="cu-item">
            <text class="cuIcon-people text-green"></text>
            <text class="text-sm">我的技能</text>
            <text class="text-bold">{{stats.mySkills}}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 任务列表 -->
    <view class="task-list margin-top">
      <view v-if="loading" class="flex justify-center align-center" style="height: 400rpx;">
        <text class="cuIcon-loading2 cuIconfont-spin text-gray"></text>
        <text class="text-gray margin-left-sm">加载中...</text>
      </view>
      
      <view v-else-if="tasks.length === 0" class="flex justify-center align-center" style="height: 400rpx;">
        <view class="text-center">
          <text class="cuIcon-infofill text-gray" style="font-size: 100rpx;"></text>
          <view class="text-gray margin-top">暂无可领取的任务</view>
        </view>
      </view>
      
      <view v-else>
        <view 
          v-for="task in tasks" 
          :key="task.id" 
          class="cu-card case margin-bottom-sm"
          @tap="viewTaskDetail(task)"
        >
          <view class="cu-item shadow">
            <view class="cu-list menu-avatar">
              <view class="cu-item">
                <view class="cu-avatar round lg" :style="{backgroundColor: task.statusColor}">
                  <text class="cuIcon-form text-white"></text>
                </view>
                <view class="content flex-sub">
                  <view class="text-black text-bold">{{task.taskNo}}</view>
                  <view class="text-gray text-sm">{{task.workTypeName}}</view>
                  <view class="text-gray text-xs margin-top-xs">
                    <text class="cuIcon-time margin-right-xs"></text>
                    {{task.planStartDate}} - {{task.planEndDate}}
                  </view>
                </view>
                <view class="action">
                  <view class="cu-tag sm" :class="task.priorityClass">{{task.priorityText}}</view>
                  <view class="margin-top-xs">
                    <button 
                      class="cu-btn bg-green sm"
                      @tap.stop="claimTask(task)"
                    >
                      领取
                    </button>
                  </view>
                </view>
              </view>
            </view>
            
            <!-- 任务详情 -->
            <view class="padding-lr">
              <view class="flex justify-between text-sm margin-bottom-sm">
                <text class="text-gray">计划数量:</text>
                <text>{{task.planQuantity}}</text>
              </view>
              <view class="flex justify-between text-sm margin-bottom-sm">
                <text class="text-gray">所属计划:</text>
                <text class="text-blue">{{task.planNo}}</text>
              </view>
              <view v-if="task.description" class="text-sm text-gray margin-bottom-sm">
                {{task.description}}
              </view>
              
              <!-- 技能匹配度 -->
              <view class="flex align-center margin-top-sm">
                <text class="text-xs text-gray margin-right-sm">技能匹配:</text>
                <view class="cu-progress round sm flex-sub">
                  <view 
                    class="bg-green" 
                    :style="{width: task.skillMatch + '%'}"
                  ></view>
                </view>
                <text class="text-xs text-gray margin-left-sm">{{task.skillMatch}}%</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 加载更多 -->
    <view v-if="hasMore && !loading" class="padding text-center">
      <button class="cu-btn bg-gray sm" @tap="loadMore">加载更多</button>
    </view>

    <!-- 筛选弹窗 -->
    <cu-modal :show="showFilterModal" @close="showFilterModal = false">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">筛选条件</view>
          <view class="action" @tap="showFilterModal = false">
            <text class="cuIcon-close text-red"></text>
          </view>
        </view>
        <view class="padding">
          <view class="cu-form-group">
            <view class="title">工种</view>
            <picker 
              :value="filter.workTypeIndex" 
              :range="workTypes" 
              range-key="name"
              @change="onWorkTypeChange"
            >
              <view class="picker">
                {{workTypes[filter.workTypeIndex].name}}
              </view>
            </picker>
          </view>
          <view class="cu-form-group">
            <view class="title">优先级</view>
            <picker 
              :value="filter.priorityIndex" 
              :range="priorities" 
              range-key="label"
              @change="onPriorityChange"
            >
              <view class="picker">
                {{priorities[filter.priorityIndex].label}}
              </view>
            </picker>
          </view>
          <view class="cu-form-group">
            <view class="title">计划开始时间</view>
            <picker 
              mode="date" 
              :value="filter.startDate" 
              @change="onStartDateChange"
            >
              <view class="picker">
                {{filter.startDate || '选择日期'}}
              </view>
            </picker>
          </view>
          <view class="padding-top">
            <button class="cu-btn bg-blue lg block margin-bottom" @tap="applyFilter">应用筛选</button>
            <button class="cu-btn bg-gray lg block" @tap="resetFilter">重置</button>
          </view>
        </view>
      </view>
    </cu-modal>

    <!-- 领取确认弹窗 -->
    <cu-modal :show="showClaimModal" @close="showClaimModal = false">
      <view class="cu-dialog">
        <view class="cu-bar bg-white justify-end">
          <view class="content">确认领取</view>
          <view class="action" @tap="showClaimModal = false">
            <text class="cuIcon-close text-red"></text>
          </view>
        </view>
        <view class="padding" v-if="selectedTask">
          <view class="text-center margin-bottom">
            <text class="text-lg text-bold">{{selectedTask.taskNo}}</text>
          </view>
          <view class="cu-list menu">
            <view class="cu-item">
              <view class="content">
                <text class="text-gray">工种</text>
              </view>
              <view class="action">
                <text>{{selectedTask.workTypeName}}</text>
              </view>
            </view>
            <view class="cu-item">
              <view class="content">
                <text class="text-gray">计划数量</text>
              </view>
              <view class="action">
                <text>{{selectedTask.planQuantity}}</text>
              </view>
            </view>
            <view class="cu-item">
              <view class="content">
                <text class="text-gray">计划工期</text>
              </view>
              <view class="action">
                <text>{{selectedTask.planStartDate}} - {{selectedTask.planEndDate}}</text>
              </view>
            </view>
          </view>
          <view class="padding-top">
            <button 
              class="cu-btn bg-green lg block"
              :loading="claimLoading"
              @tap="confirmClaim"
            >
              确认领取
            </button>
          </view>
        </view>
      </view>
    </cu-modal>
  </view>
</template>

<script>
import productionPlanV2 from '@/api/mes/productionPlanV2.js'
import authService from '@/common/auth/authService.js'

export default {
  data() {
    return {
      tasks: [],
      loading: false,
      hasMore: true,
      searchKeyword: '',
      showFilterModal: false,
      showClaimModal: false,
      selectedTask: null,
      claimLoading: false,
      
      // 统计信息
      stats: {
        available: 0,
        urgent: 0,
        mySkills: 0
      },
      
      // 筛选条件
      filter: {
        workTypeIndex: 0,
        priorityIndex: 0,
        startDate: ''
      },
      
      // 筛选选项
      workTypes: [
        { id: '', name: '全部工种' }
      ],
      priorities: [
        { value: '', label: '全部优先级' },
        { value: 'high', label: '高优先级' },
        { value: 'medium', label: '中优先级' },
        { value: 'low', label: '低优先级' }
      ],
      
      // 分页参数
      pageNum: 1,
      pageSize: 10
    }
  },
  
  onLoad() {
    this.loadWorkTypes()
    this.loadTasks()
    this.loadStats()
  },
  
  methods: {
    // 加载工种列表
    async loadWorkTypes() {
      try {
        const response = await productionPlanV2.getWorkTypes()
        this.workTypes = [
          { id: '', name: '全部工种' },
          ...response.data
        ]
      } catch (error) {
        console.error('加载工种失败:', error)
      }
    },
    
    // 加载可领取任务
    async loadTasks(reset = false) {
      if (this.loading) return
      
      if (reset) {
        this.pageNum = 1
        this.tasks = []
        this.hasMore = true
      }
      
      this.loading = true
      try {
        const params = {
          pageNum: this.pageNum,
          pageSize: this.pageSize,
          keyword: this.searchKeyword,
          workTypeId: this.workTypes[this.filter.workTypeIndex].id,
          priority: this.priorities[this.filter.priorityIndex].value,
          startDate: this.filter.startDate
        }
        
        const response = await productionPlanV2.getAvailableTasks(params)
        const newTasks = response.data.records.map(task => this.processTaskData(task))
        
        if (reset) {
          this.tasks = newTasks
        } else {
          this.tasks.push(...newTasks)
        }
        
        this.hasMore = response.data.current < response.data.pages
        this.pageNum++
      } catch (error) {
        console.error('加载任务失败:', error)
        uni.showToast({
          title: '加载失败',
          icon: 'none'
        })
      } finally {
        this.loading = false
      }
    },
    
    // 加载统计信息
    async loadStats() {
      try {
        const response = await productionPlanV2.getAvailableTaskStats()
        this.stats = response.data
      } catch (error) {
        console.error('加载统计失败:', error)
      }
    },
    
    // 处理任务数据
    processTaskData(task) {
      return {
        ...task,
        statusColor: this.calculateStatusColor(task),
        priorityClass: this.calculatePriorityClass(task),
        priorityText: this.calculatePriorityText(task),
        skillMatch: this.calculateSkillMatch(task)
      }
    },
    
    // 计算状态颜色
    calculateStatusColor(task) {
      return '#34c759' // 绿色表示可领取
    },
    
    // 计算优先级样式类
    calculatePriorityClass(task) {
      const priorityMap = {
        'high': 'bg-red',
        'medium': 'bg-orange',
        'low': 'bg-blue'
      }
      return priorityMap[task.priority] || 'bg-gray'
    },
    
    // 计算优先级文本
    calculatePriorityText(task) {
      const priorityMap = {
        'high': '高',
        'medium': '中',
        'low': '低'
      }
      return priorityMap[task.priority] || '未设置'
    },
    
    // 计算技能匹配度
    calculateSkillMatch(task) {
      // 这里应该根据当前用户的技能和任务要求计算匹配度
      // 暂时返回随机值作为示例
      return Math.floor(Math.random() * 40) + 60
    },
    
    // 搜索输入
    onSearchInput() {
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.loadTasks(true)
      }, 500)
    },
    
    // 工种选择变化
    onWorkTypeChange(e) {
      this.filter.workTypeIndex = e.detail.value
    },
    
    // 优先级选择变化
    onPriorityChange(e) {
      this.filter.priorityIndex = e.detail.value
    },
    
    // 开始日期选择变化
    onStartDateChange(e) {
      this.filter.startDate = e.detail.value
    },
    
    // 应用筛选
    applyFilter() {
      this.showFilterModal = false
      this.loadTasks(true)
    },
    
    // 重置筛选
    resetFilter() {
      this.filter = {
        workTypeIndex: 0,
        priorityIndex: 0,
        startDate: ''
      }
      this.searchKeyword = ''
      this.showFilterModal = false
      this.loadTasks(true)
    },
    
    // 刷新数据
    async refreshData() {
      await Promise.all([
        this.loadTasks(true),
        this.loadStats()
      ])
      uni.showToast({
        title: '刷新成功',
        icon: 'success'
      })
    },
    
    // 加载更多
    loadMore() {
      this.loadTasks()
    },
    
    // 查看任务详情
    viewTaskDetail(task) {
      uni.navigateTo({
        url: `/pages/production/task/detail?id=${task.id}`
      })
    },
    
    // 领取任务
    claimTask(task) {
      this.selectedTask = task
      this.showClaimModal = true
    },
    
    // 确认领取
    async confirmClaim() {
      this.claimLoading = true
      try {
        await productionPlanV2.claimTask(this.selectedTask.id)
        uni.showToast({
          title: '领取成功',
          icon: 'success'
        })
        
        this.showClaimModal = false
        this.selectedTask = null
        
        // 刷新列表和统计
        await Promise.all([
          this.loadTasks(true),
          this.loadStats()
        ])
      } catch (error) {
        console.error('领取任务失败:', error)
        uni.showToast({
          title: '领取失败',
          icon: 'none'
        })
      } finally {
        this.claimLoading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.available-tasks-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 40rpx;
}

.task-list {
  padding: 0 20rpx;
}

.cu-progress.sm {
  height: 8rpx;
}

.cu-modal {
  .cu-dialog {
    border-radius: 20rpx;
    overflow: hidden;
  }
}

.cu-form-group {
  .title {
    min-width: 150rpx;
  }
  
  .picker {
    flex: 1;
    text-align: right;
    color: #333;
  }
}
</style>
